package cn.edu.scau.cmi.heyaqing.hibernate.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import cn.edu.scau.cmi.heyaqing.hibernate.domain.Student;

public class StudentDAO {
	public void save(Student stu) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.save(stu);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
	}

	public void delete(Student stu) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.delete(stu);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();

	}

	public void update(Student stu) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.update(stu);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
	}

	public Student get(long id) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Student stu = (Student) openSession.get("cn.edu.scau.cmi.heyaqing.hibernate.domain.Student", id);
		openSession.close();
		buildSessionFactory.close();
		return stu;
	}

	public List<Student> list() {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Query<Student> query = openSession.createSQLQuery("select * from student").addEntity(Student.class);
		List<Student> list = query.list();
		openSession.close();
		buildSessionFactory.close();
		return list;
	}

}